package com.ego.listener;

import com.ego.service.CartService;
import com.ego.service.impl.CartServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class OrderListener {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 下单成功，删除购物车
     *
     * @throws Exception
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "ego.cart.delete.queue", durable = "true"),
            exchange = @Exchange(
                    value = "ego.order.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC),
            key = {"order.submit"}))
    public void deleteCart(Map<String,Object> data) {
        if (MapUtils.isEmpty(data)) {
            log.error("订单消息有误");
            return;
        }
        List<Long> skuIdList = (List<Long>) data.get("skuIdList");
        Long userId = (Long) data.get("userId");
        skuIdList.forEach(skuId->stringRedisTemplate.opsForHash().delete(CartServiceImpl.KEY_PREFIX + userId, skuId.toString()));

        log.info("清除用户:{}已下单购物项:{}",userId,skuIdList.toString());
    }
}
